/**
 * 新增、编辑赔偿单
 * type 0 临时 1 结案
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { useRequest } from '@umijs/hooks';
import { Card, Input, Radio, Button, Select, InputNumber, message } from 'antd';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import {
  auditPkgInfo,
  pkgAuditTypeJudge,
  listNone,
  updatePkgOrder
} from './service';
import { Const } from '../Const';

import AuthComponent from '@/components/Authorized/AuthComponent';
import AuditPopup from './components/AuditPopup';

const FormItem = Form.Item;
const { Option } = Select;

class PrivateData {
  static radioTypeMap = {
    0: { text: '', arr: [], rmb: '' },
    1: { text: '金额', arr: ['paymentMoney'], rmb: 'paymentMoney' },
    2: { text: '运输费用', arr: ['transportPay'], rmb: 'transportPay' },
    3: { text: '超重', arr: ['overWeightPay'], rmb: 'overWeightPay' },
    4: { text: '汇款', arr: ['payee', 'payeePhone', 'payeeMoney', 'payeeAccount', 'payeeBank', 'bankCardProvince', 'bankCardArea', 'bankCardAreaNo', 'payeeUse'], rmb: 'payeeMoney' },
    5: { text: '箱包', arr: ['pkgId', 'pkgCount', 'pkgPrice', 'orderRemark'], rmb: 'pkgPrice' }
  };
  static numTime = null;
  static submitForm = {};
}

const AddEditCompensation = props => {

  // type 0临时 1结案
  const { form, location: { state: { type, itemData, detailData = {}, status, ownerType = 0 } } } = props;

  const [radioTypeVal, setRadioTypeVal] = useState(1); // 类型 - 默认金额

  const [auditPopupVisible, setAuditPopupVisible] = useState(false); // 审核人弹窗
  const [roleName, setRoleName] = useState('');

  useEffect(() => {
    if (status === 'edit') {
      for (let key in PrivateData.radioTypeMap) {
        if (key === 0) continue;
        const keyName = PrivateData.radioTypeMap[key].rmb;
        if (detailData[keyName]) {
          setRadioTypeVal(+key);
          break;
        }
      }
    }
  }, [status, detailData])

  // 获取箱包列表
  const { run: runListNone, data: xiangbaoList = [] } = useRequest(listNone, {
    onSuccess (res) {
      console.log(res, '箱包列表');
    }
  })

  // 发起赔偿
  const { run: runAuditPkgInfo, loading: addLoading } = useRequest(data => auditPkgInfo(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '发起赔偿');
      Const.setIsNeedGetList(ownerType);
      router.push({
        pathname: Const.commonUrl + '/inPortBaggageManagement/compensationDetail',
        state: {
          type: type,
          orderId: res || '',
          ownerType: ownerType
        }
      });
    }
  });

  // 修改赔偿
  const { run: runUpdatePkgOrder, loading: editLoading } = useRequest(data => updatePkgOrder(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '修改赔偿');
      Const.setIsNeedGetList(ownerType);
      router.push({
        pathname: Const.commonUrl + '/inPortBaggageManagement/compensationDetail',
        state: {
          type: type,
          orderId: res || '',
          ownerType: ownerType
        }
      });
    }
  })

  // 审核人弹窗 - 打开
  const auditPopupOpen = useCallback(() => {
    setAuditPopupVisible(true);
  }, []);
  // 审核人弹窗 - 关闭
  const auditPopupClose = useCallback(() => {
    setAuditPopupVisible(false);
  }, []);
  // 审核人弹窗 - 取消
  const auditPopupCancel = useCallback(() => {
    auditPopupClose();
  }, []);
  // 审核人弹窗 - 提交
  const auditPopupSubmit = useCallback(val => {
    console.log(val, '审核人弹窗 - 提交');
    auditPopupClose();
    if (status === 'add') {
      runAuditPkgInfo({
        ...PrivateData.submitForm,
        auditIds: val.join(','),
      });
    } else {
      runUpdatePkgOrder({
        ...PrivateData.submitForm,
        auditIds: val.join(','),
        orderId: detailData.orderId
      })
    }
  }, [detailData]);

  // 判断审核类型
  const { run: runPkgAuditTypeJudge } = useRequest(data => pkgAuditTypeJudge(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '判断审核类型');
      let data = res || {};
      PrivateData.submitForm.airportType = data.airportType; // 航站类型：0成都 1分公司 2无人航站
      PrivateData.submitForm.auditType = data.auditType; // 审核类型：0自动审核 1手动审核
      if (+data.auditType === 1) {
        setRoleName(data.firstLevelAuditRoleName)
        auditPopupOpen();
      } else {
        if (status === 'add') {
          runAuditPkgInfo({
            ...PrivateData.submitForm,
            auditIds: '',
          });
        } else {
          runUpdatePkgOrder({
            ...PrivateData.submitForm,
            auditIds: '',
            orderId: detailData.orderId
          })
        }
      }
    }
  });

  const numChange = useCallback(val => {
    clearTimeout(PrivateData.numTime);
    PrivateData.numTime = setTimeout(() => {
      if (val > 100000000) val = 100000000;
      form.setFieldsValue({
        paymentDetail: val ? Const.numberChinese(val) : ''
      })
    }, 100);
  }, [form]);

  // 金额类型改变
  const radioTypeChange = useCallback(e => {
    const val = e.target.value;
    setRadioTypeVal(val);
    let _key = PrivateData.radioTypeMap[val].rmb || ''
    let moneyNum = form.getFieldValue(_key);
    setTimeout(() => {
      form.setFieldsValue({
        paymentDetail: moneyNum ? Const.numberChinese(moneyNum) : ''
      })
    }, 0);
  }, [form]);

  // 箱包尺寸改变
  const pkgIdChange = useCallback((val) => {
    let numReg = /^[0-9]*$/;
    let pkgCount = form.getFieldValue('pkgCount');
    let pkgItem = xiangbaoList.filter(item => item.id === val);
    PrivateData.submitForm.pkgSize = pkgItem[0].pkgSize || '';
    if (numReg.test(pkgCount) && pkgItem.length === 1) {
      let pkgPrice = pkgCount * (+pkgItem[0].pkgPrice);
      form.setFieldsValue({
        pkgPrice,
        paymentDetail: Const.numberChinese(pkgPrice)
      });
    }
  }, [form, xiangbaoList]);

  // 箱包数量改变
  const pkgCountChange = useCallback((val) => {
    let numReg = /^[0-9]*$/;
    let pkgId = form.getFieldValue('pkgId');
    let pkgItem = xiangbaoList.filter(item => item.id === pkgId);
    if (numReg.test(val) && pkgItem.length === 1) {
      let pkgPrice = val * (+pkgItem[0].pkgPrice);
      form.setFieldsValue({
        pkgPrice,
        paymentDetail: Const.numberChinese(pkgPrice)
      });
    }
  }, [form, xiangbaoList]);

  // 防止重复提交
  const saveFormStatus = useMemo(() => {
    return (addLoading || editLoading);
  }, [addLoading, editLoading]);

  // 取消
  const cancelIt = useCallback(() => {
    router.goBack();
  }, []);
  // 提交
  const submitIt = useCallback(() => {
    if (saveFormStatus) {
      message.warning('请勿重复提交');
      return;
    }
    form.validateFields(['paymentReason', 'paymentDetail', ...PrivateData.radioTypeMap[radioTypeVal].arr], (err, fieldsValue) => {
      if (err) return;
      let obj = {
        accidentId: itemData.accidentId,
        compensateType: type, // 0临时 1结案
        radioType: radioTypeVal,
        ...fieldsValue
      };
      delete obj.info;
      PrivateData.submitForm = {
        ...obj
      };
      if (radioTypeVal === 5) {
        let pkgItem = xiangbaoList.filter(item => item.id === PrivateData.submitForm.pkgId);
        PrivateData.submitForm.pkgSize = pkgItem[0].pkgSize || '';
      }
      console.log(PrivateData.submitForm, 'PrivateData.submitForm')
      let _key = PrivateData.radioTypeMap[radioTypeVal].rmb || ''
      runPkgAuditTypeJudge({
        accidentId: itemData.accidentId,
        payMoney: fieldsValue[_key]
      });
    })
  }, [form, radioTypeVal, itemData, type, xiangbaoList, saveFormStatus]);

  return (
    <div className={styles.temporaryCompensationContent}>
      <Card title="填写信息" style={{ width: '100%' }}>
        <div className={styles.formContent}>
          <FormItem label="旅客姓名">
            {form.getFieldDecorator('info.paxName', {
              rules: [],
              initialValue: itemData.paxName || ''
            })(
              <Input disabled placeholder="请输入" />
            )}
          </FormItem>
          <FormItem label="客票号码">
            {form.getFieldDecorator('info.tktNo', {
              rules: [],
              initialValue: itemData.tktNo || ''
            })(
              <Input disabled placeholder="请输入" />
            )}
          </FormItem>
        </div>
        <div className={styles.formContent}>
          <FormItem label="证件类型">
            {form.getFieldDecorator('info.idType', {
              rules: [],
              initialValue: itemData.idType || ''
            })(
              <Select
                allowClear
                placeholder="请选择"
                disabled
                style={{ width: '100%' }}
              >
                {Const.idTypeListForSearch.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
              </Select>
            )}
          </FormItem>
          <FormItem label="证件号码">
            {form.getFieldDecorator('info.idNo', {
              rules: [],
              initialValue: itemData.idNo || ''
            })(
              <Input disabled placeholder="请输入" />
            )}
          </FormItem>
        </div>
        <div className={styles.formContent}>
          <FormItem label="航班号/日期">
            {form.getFieldDecorator('info.flightInfo', {
              rules: [],
              initialValue: ((itemData.flightNo || '-') + '/' + (itemData.flightDate || '-')) || ''
            })(
              <Input disabled placeholder="请输入" />
            )}
          </FormItem>
          <FormItem label="航程">
            {form.getFieldDecorator('info.voyage', {
              rules: [],
              initialValue: itemData.voyage || ''
            })(
              <Input disabled placeholder="请输入" />
            )}
          </FormItem>
        </div>
        <div className={styles.formContent}>
          <FormItem label="行李牌号码">
            {form.getFieldDecorator('info.pkgNo', {
              rules: [
                { pattern: /^([A-Z\d]{6}|[A-Z\d]{8}|[A-Z\d]{10})$/, message: '行李号不正确，正确格式如123456、AA123456、1234567890' },
              ],
              initialValue: itemData.pkgNo || ''
            })(
              <Input disabled placeholder="请输入" />
            )}
          </FormItem>
          <FormItem label="飞机号/型号">
            {form.getFieldDecorator('info.planeInfo', {
              rules: [],
              initialValue: ((itemData.planeCode || '-') + '/' + (itemData.acType || '-')) || ''
            })(
              <Input disabled placeholder="请输入" />
            )}
          </FormItem>
        </div>
      </Card>
      <Card title="赔偿信息" style={{ width: '100%' }}>
        <div>
          <FormItem label="赔偿原因">
            {form.getFieldDecorator('paymentReason', {
              rules: [
                { required: true, message: '请输入赔偿原因' }
              ],
              initialValue: detailData.paymentReason || ''
            })(
              <Input placeholder="请输入" maxLength={200} />
            )}
          </FormItem>
        </div>
        <div>
          <FormItem label="赔偿明细">
            {form.getFieldDecorator('paymentDetail', {
              rules: [
                { required: true, message: '请输入赔偿明细' }
              ],
              initialValue: detailData.paymentDetail || ''
            })(
              <Input disabled placeholder="请输入" maxLength={200} />
            )}
          </FormItem>
        </div>
        <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}>
            <Radio
              defaultChecked={false}
              value={1}
              checked={radioTypeVal === 1}
              onChange={radioTypeChange}>
              金额
            </Radio>
          </div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="赔偿现金">
                {form.getFieldDecorator('paymentMoney', {
                  rules: [
                    // { validator: PrivateData.requiredValidator['paymentMoneyValidator'] }
                    { required: true, message: '请输入赔偿金额' },
                    { pattern: /^\d*$/, message: '请输入自然数赔偿金额' }
                  ],
                  initialValue: detailData.paymentMoney || ''
                })(
                  <InputNumber
                    disabled={radioTypeVal !== 1}
                    placeholder="请输入"
                    min={0}
                    step={1}
                    max={Const.inputNumMax}
                    onChange={numChange}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
            </div>
          </div>
        </div>
        {type === 1 && <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}>
            <Radio
              defaultChecked={false}
              value={2}
              checked={radioTypeVal === 2}
              onChange={radioTypeChange}>
              运输费用
            </Radio>
          </div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="运输费用">
                {form.getFieldDecorator('transportPay', {
                  rules: [
                    { required: true, message: '请输入运输费用' },
                    { pattern: /^\d*$/, message: '请输入自然数运输费用' }
                  ],
                  initialValue: detailData.transportPay || ''
                })(
                  <InputNumber
                    disabled={radioTypeVal !== 2}
                    placeholder="请输入"
                    min={0}
                    max={Const.inputNumMax}
                    onChange={numChange}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
            </div>
          </div>
        </div>}
        {type === 1 && <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}>
            <Radio
              defaultChecked={false}
              value={3}
              checked={radioTypeVal === 3}
              onChange={radioTypeChange}>
              超重
            </Radio>
          </div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="超重费用">
                {form.getFieldDecorator('overWeightPay', {
                  rules: [
                    { required: true, message: '请输入超重费用' },
                    { pattern: /^\d*$/, message: '请输入自然数超重费用' }
                  ],
                  initialValue: detailData.overWeightPay || ''
                })(
                  <InputNumber
                    disabled={radioTypeVal !== 3}
                    placeholder="请输入"
                    min={0}
                    max={Const.inputNumMax}
                    onChange={numChange}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
            </div>
          </div>
        </div>}
        <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}>
            <Radio
              defaultChecked={false}
              value={4}
              checked={radioTypeVal === 4}
              onChange={radioTypeChange}>
              汇款
            </Radio>
          </div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="收款人">
                {form.getFieldDecorator('payee', {
                  rules: [
                    // { validator: PrivateData.requiredValidator['payeeValidator'] }
                    { required: true, message: '请输入收款人' }
                  ],
                  initialValue: detailData.payee || ''
                })(
                  <Input disabled={radioTypeVal !== 4} placeholder="请输入" maxLength={20} />
                )}
              </FormItem>
              <FormItem label="收款人电话">
                {form.getFieldDecorator('payeePhone', {
                  rules: [
                    // { validator: PrivateData.requiredValidator['payeePhoneValidator'] }
                    { required: true, message: '请输入收款人电话' },
                    { pattern: Const.phoneMobileReg, message: '请输入正确的格式'}
                  ],
                  initialValue: detailData.payeePhone || ''
                })(
                  <Input disabled={radioTypeVal !== 4} placeholder="请输入" maxLength={13} />
                )}
              </FormItem>
              <FormItem label="金额">
                {form.getFieldDecorator('payeeMoney', {
                  rules: [
                    { required: true, message: '请输入金额' },
                    { pattern: /^\d*$/, message: '请输入自然数金额' }
                  ],
                  initialValue: detailData.payeeMoney || ''
                })(
                  <InputNumber
                    disabled={radioTypeVal !== 4}
                    min={0}
                    max={Const.inputNumMax}
                    placeholder="请输入"
                    onChange={numChange}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
            </div>
          </div>
        </div>
        <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}></div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="收款账户">
                {form.getFieldDecorator('payeeAccount', {
                  rules: [
                    { required: true, message: '请输入收款账户' }
                  ],
                  initialValue: detailData.payeeAccount || ''
                })(
                  <Input disabled={radioTypeVal !== 4} placeholder="请输入" maxLength={50} />
                )}
              </FormItem>
              <FormItem label="收款银行">
                {form.getFieldDecorator('payeeBank', {
                  rules: [
                    { required: true, message: '请输入收款银行' }
                  ],
                  initialValue: detailData.payeeBank || ''
                })(
                  <Select
                    allowClear
                    placeholder="请选择"
                    disabled={radioTypeVal !== 4}
                    style={{ width: '100%' }}
                  >
                    {Const.bankList.map(item => <Option key={item} value={item}>{item}</Option>)}
                  </Select>
                )}
              </FormItem>
              <FormItem label="银行卡所属省份">
                {form.getFieldDecorator('bankCardProvince', {
                  rules: [],
                  initialValue: detailData.bankCardProvince || ''
                })(
                  <Select
                    allowClear
                    placeholder="请选择"
                    disabled={radioTypeVal !== 4}
                    style={{ width: '100%' }}
                  >
                    {Const.provinceList.map(item => <Option key={item} value={item}>{item}</Option>)}
                  </Select>
                )}
              </FormItem>
            </div>
          </div>
        </div>
        <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}></div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="银行卡所属地区">
                {form.getFieldDecorator('bankCardArea', {
                  rules: [],
                  initialValue: detailData.bankCardArea || ''
                })(
                  <Input disabled={radioTypeVal !== 4} placeholder="请输入" maxLength={50} />
                )}
              </FormItem>
              <FormItem label="银行卡所属地区号码">
                {form.getFieldDecorator('bankCardAreaNo', {
                  rules: [],
                  initialValue: detailData.bankCardAreaNo || ''
                })(
                  <Input disabled={radioTypeVal !== 4} placeholder="请输入" maxLength={50} />
                )}
              </FormItem>
              <FormItem label="汇款用途">
                {form.getFieldDecorator('payeeUse', {
                  rules: [],
                  initialValue: detailData.payeeUse || ''
                })(
                  <Select
                    allowClear
                    placeholder="请选择"
                    disabled={radioTypeVal !== 4}
                    style={{ width: '100%' }}
                  >
                    {Const.payeeUseList.map(item => <Option key={item} value={item}>{item}</Option>)}
                  </Select>
                )}
              </FormItem>
            </div>
          </div>
        </div>
        {type === 1 && <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}>
            <Radio
              defaultChecked={false}
              value={5}
              checked={radioTypeVal === 5}
              onChange={radioTypeChange}>
              箱包
            </Radio>
          </div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="箱包尺寸">
                {form.getFieldDecorator('pkgId', {
                  rules: [
                    { required: true, message: '请选择箱包尺寸' }
                  ],
                  initialValue: detailData.pkgId || ''
                })(
                  <Select
                    allowClear
                    placeholder="请选择"
                    disabled={radioTypeVal !== 5}
                    onChange={pkgIdChange}
                    style={{ width: '100%' }}
                  >
                    {xiangbaoList.map(item => <Option key={item.id} value={item.id}>{item.pkgSize}</Option>)}
                  </Select>
                )}
              </FormItem>
              <FormItem label="箱包数量">
                {form.getFieldDecorator('pkgCount', {
                  rules: [
                    { required: true, message: '请输入箱包数量' },
                    { pattern: /^\d*$/, message: '请输入自然数箱包数量' }
                  ],
                  initialValue: detailData.pkgCount || ''
                })(
                  <InputNumber
                    disabled={radioTypeVal !== 5}
                    placeholder="请输入"
                    min={1}
                    max={Const.inputNumMax}
                    onChange={pkgCountChange}
                    style={{ width: '100%' }} />
                )}
              </FormItem>
              <FormItem label="补偿成本">
                {form.getFieldDecorator('pkgPrice', {
                  rules: [
                    { required: true, message: '请输入补偿成本' }
                  ],
                  initialValue: detailData.pkgPrice || ''
                })(
                  <Input disabled placeholder="请输入" />
                )}
              </FormItem>
            </div>
          </div>
        </div>}
        {type === 1 && <div className={styles.compensationInfoContent}>
          <div className={styles.compensationInfoContentLeft}></div>
          <div className={styles.compensationInfoContentRight}>
            <div className={styles.formContentOther}>
              <FormItem label="备注">
                {form.getFieldDecorator('orderRemark', {
                  rules: [],
                  initialValue: detailData.orderRemark || ''
                })(
                  <Input placeholder="请输入" disabled={radioTypeVal !== 5} maxLength={200} />
                )}
              </FormItem>
            </div>
          </div>
        </div>}
      </Card>
      <div className={styles.btnBox}>
        <Button type="primary" style={{ marginRight: '10px' }} onClick={cancelIt}>取 消</Button>
        <Button type="primary" style={{ marginRight: '10px' }} onClick={submitIt}>提 交</Button>
      </div>

      <AuditPopup
        modalVisible={auditPopupVisible}
        onCancel={auditPopupCancel}
        onSubmit={auditPopupSubmit}
        roleName={roleName}
      ></AuditPopup>
    </div>
  )
}

export default Form.create()(AddEditCompensation);

